package com.appspot.yusupova.verses;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.stdimpl.GCacheFactory;

public class CachedVerseMap {
    
    private static final Logger logger = Logger.getLogger(CachedVerseMap.class.getName());

    @SuppressWarnings("unchecked")
    public static String get(String phraseText) {
        Cache cache = null;
        Map<Object, Object> props = new HashMap<Object, Object>();
        props.put(GCacheFactory.EXPIRATION_DELTA, 3600);
        props.put(MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT, true);
        try {
            CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
            cache = cacheFactory.createCache(props);
        } catch (CacheException e) {
            logger.log(Level.SEVERE, "Error while getting cache value:", e);
        }
        String result = (String) cache.get(phraseText);
        if (result == null) {
            result = VerseMap.get(phraseText);
            cache.put(phraseText, result);
        } 
        return result;
    }

}
